<!--
 * @Description: 
 * @Version: 1.0
 * @Autor: chen_yt
 * @Date: 2022-07-12 13:45:40
 * @LastEditors: chen_yt
 * @LastEditTime: 2022-08-09 15:52:55
-->
<template>
  <fks-drawer
    :visible.sync="visible"
    direction="rtl"
    :before-close="handleClose"
    custom-class="tenant-drawer"
    :show-close="false"
    :withHeader="false"
    size="656px"
    destroy-on-close
  >
    <div class="tenant-drawer-container">
      <div class="tenant-drawer-header">
        <template v-if="type == 'add'">
          <i class="fks-icon-plus" />{{ LANG.ADD_TENANT_MESSAGE }}
        </template>
        <template v-else>
          <i class="fks-icon-edit" />{{ LANG.EDIT_TENANT_MESSAGE }}
        </template>
      </div>
      <div class="tenant-drawer-body">
        <!-- 放个form -->
        <fks-form ref="form" :model="form" :rules="rules">
          <div class="form-divider-title">
            <i class="fks-icon-text"></i>
            {{ LANG.BASIC_MESSAGE }}
          </div>
          <fks-form-item :label="LANG.TENANT_NAME" prop="clientName">
            <fks-input
              v-model="form.clientName"
              maxlength="50"
              show-word-limit
            ></fks-input>
          </fks-form-item>
          <fks-form-item :label="LANG.REMARK" prop="remark">
            <fks-input
              v-model="form.remark"
              type="textarea"
              maxlength="250"
              show-word-limit
              :autosize="{ minRows: 4, maxRows: 6 }"
            ></fks-input>
          </fks-form-item>

          <div class="form-divider-title">
            <i class="fks-icon-data-permission"></i>
            {{ LANG.MASTER_DATA_SETTING }}
          </div>
          <fks-form-item :label="LANG.MASTER_DATA" prop="dataMode">
            <fks-checkbox-group v-model="form.dataMode">
              <fks-checkbox
                v-for="item in dataModeList"
                :key="item.label"
                :label="item.label"
                >{{ item.name }}</fks-checkbox
              >
            </fks-checkbox-group>
            <div class="item-sp-tip">
              {{ LANG.MASTER_DATA_TIP }}
            </div>
          </fks-form-item>

          <div class="form-divider-title" v-if="chosedMasterUserData">
            <i class="fks-icon-user"></i>
            {{ LANG.TENANT_MANAGER_SETTING }}
          </div>
          <fks-form-item
            :label="LANG.TENANT_MANAGER"
            prop="manager"
            v-if="chosedMasterUserData"
          >
            <fks-user-selector
              url
              custom-class="my-custom"
              width="60%"
              @change="selectMember"
              :username.sync="form.manager"
              :userfullname.sync="form.managerFullname"
            ></fks-user-selector>
            <div class="item-sp-tip" style="margin-top: 10px">
              {{ LANG.TENANT_MANAGER_TIP }}
            </div>
          </fks-form-item>

          <div class="form-divider-title">
            <i class="fks-icon-department"></i>
            {{ LANG.PORTAL_MODE }}
          </div>
          <fks-form-item :label="LANG.MULITI_PORTAL_MODE" prop="multiPortal">
            <fks-switch v-model="form.multiPortal"></fks-switch>
            <div class="item-sp-tip" style="margin-top: 8px">
              {{ LANG.MULITI_PORTAL_TIP }}
            </div>
          </fks-form-item>

          <div class="form-divider-title">
            <i class="fks-icon-menu"></i>
            {{ LANG.MENU_SETTING }}
          </div>
          <fks-form-item :label="LANG.MENU" prop="selectedMenu">
            <simple-menu
              :menu.sync="form.selectedMenu"
              v-if="visible"
            ></simple-menu>
          </fks-form-item>
        </fks-form>
      </div>
      <div class="tenant-drawer-footer">
        <div class="operation-manual">
          <fks-button text @click="openTenantNoteBook" icon="fks-icon-content">
            {{ LANG.OPERATION_MANUAL }}
          </fks-button>
        </div>
        <div class="button-container">
          <fks-button
            icon="fks-icon-close"
            @click="handleClose"
            :loading="isSubmiting"
          >
            {{ LANG.CANCEL }}
          </fks-button>
          <fks-button
            type="primary"
            icon="fks-icon-check"
            @click="submit"
            :loading="isSubmiting"
          >
            {{ LANG.SAVE }}
          </fks-button>
        </div>
      </div>
    </div>
    <PwdConfirm
      :visible.sync="pwdConfirmVisible"
      v-if="pwdConfirmVisible"
      :userInfo="tenantManagerInfo"
      @hasRecord="hasRecord"
    ></PwdConfirm>
  </fks-drawer>
</template>
<script>
import { initTenant } from './api'
import { DATA_MODE_TYPE, MASTER_DATA_TYPE } from '@/config/enums'
import SimpleMenu from './Menu'
import { LATEST_CLIENT_CONFIG } from '@/store/State/stateTypes'
import deepmerge from 'deepmerge'
import { matchFormatToTimestamp } from '@/utils/timezone'
import PwdConfirm from './PwdConfirm'

export default {
  name: 'TenantInit',
  components: { SimpleMenu, PwdConfirm },
  props: {
    data: {
      type: Object,
      default() {
        return {
          clientName: ''
        }
      }
    },
    type: {
      type: String,
      default: 'add'
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        dataMode: [],
        selectedMenu: [],
        clientName: '',
        remark: '',
        manager: '',
        managerFullname: '',
        multiPortal: false
      },
      pwdConfirmVisible: false,
      tenantManagerInfo: {},
      isSubmiting: false
    }
  },
  computed: {
    latestClientConfig() {
      return this.$store.state[LATEST_CLIENT_CONFIG]
    },
    isShowMultiPortalTip() {
      let dataMode = this.form.dataMode ?? []
      return this.form.multiPortal && dataMode.includes(MASTER_DATA_TYPE.ORG)
    },
    dataModeList() {
      return [
        { label: MASTER_DATA_TYPE.USER, name: this.LANG.USER_DATA },
        { label: MASTER_DATA_TYPE.ORG, name: this.LANG.ORG_DATA },
        { label: MASTER_DATA_TYPE.DIC, name: this.LANG.DIC_DATA }
      ]
    },
    chosedMasterUserData() {
      let dataMode = this.form.dataMode ?? []
      return dataMode.includes(MASTER_DATA_TYPE.USER)
    },
    rules() {
      return {
        clientName: [
          {
            required: true,
            trigger: 'blur'
          }
        ],
        manager: [
          {
            required: this.chosedMasterUserData,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {},
  mounted() {},
  methods: {
    selectMember(){
      this.$refs.form.clearValidate('manager')
    },
    clearData() {
      this.form = {
        dataMode: [],
        selectedMenu: [],
        clientName: '',
        remark: '',
        manager: '',
        managerFullname: '',
        multiPortal: false
      }
      this.pwdConfirmVisible = false
      this.tenantManagerInfo = {}
      this.isSubmiting = false
      this.$refs['form'].resetFields()
    },

    hasRecord() {
      this.pwdConfirmVisible = false
      this.tenantManagerInfo = {}
      this.$emit('onSave', this.type)
      this.handleClose()
    },

    handleClose() {
      this.$emit('update:visible', false)
      this.clearData()
    },

    initTenant() {
      let dataMode = {}
      this.dataModeList.forEach((item) => {
        dataMode[item.label] = this.form.dataMode.includes(item.label)
          ? DATA_MODE_TYPE.MASTER
          : DATA_MODE_TYPE.TENANT
      })

      let {
        selectedMenu: initMenuIdList,
        multiPortal,
        clientName,
        manager: adminUserName,
        remark
      } = this.form

      let advancedConfig = { multiPortal }
      let additionalInformation = deepmerge(
        this.latestClientConfig.additionalInformation,
        { dataMode, advancedConfig }
      )

      additionalInformation = JSON.parse(
        matchFormatToTimestamp(JSON.stringify(additionalInformation))
      )

      let data = {
        initMenuIdList,
        clientName,
        remark,
        additionalInformation,
        adminUserName: this.chosedMasterUserData ? adminUserName : ''
      }

      this.isSubmiting = true
      initTenant(data)
        .then((res) => {
          if (!res.status || !res.data) {
            return
          }
          let { adminUserName, adminUserPassword } = res.data
          if (adminUserPassword) {
            this.showAdminMessage(adminUserName, adminUserPassword)
            return
          }

          this.$message({
            message: this.LANG.CREATE_TENANT_SUCCESS,
            type: 'success'
          })
          this.$emit('onSave', this.type)
          this.handleClose()
        })
        .catch((e) => {
          this.$message({
            message: this.LANG.CREATE_TENANT_FAILURE,
            type: 'error'
          })
        })
        .finally(() => {
          this.isSubmiting = false
        })
    },

    /**
     * @description: 提示一下密码
     */
    showAdminMessage(name, password) {
      this.tenantManagerInfo = {
        name,
        password
      }
      this.pwdConfirmVisible = true
    },

    /**
     * @description: 保存应用数据
     */
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.initTenant()
        } else {
          this.$message({
            type: 'warning',
            message: this.LANG.INCOMPLETE_FILLING
          })
        }
      })
    },

    openTenantNoteBook() {
      window.open(' https://fawkes.cybereng.com/doc', '_blank')
    }
  }
}
</script>
<style lang="scss" scoped>
.tenant-drawer {
  &-container {
    margin: 0;
    height: 100vh;
    position: relative;
    display: flex;
    flex-direction: column;
  }
  &-header {
    padding: 16px 16px;
    border-bottom: 1px #eeeeee solid;
    flex-shrink: 0;
    flex-grow: 0;

    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
    line-height: 22px;
    i {
      margin-right: 8px;
      font-size: 20px;
      color: var(--theme-color);
    }
  }
  &-body {
    flex-shrink: 1;
    flex-grow: 1;
    overflow-y: auto;
    overflow-x: hidden;
    .fks-form {
      margin-right: 0px;
      margin-left: 0;
    }
    .fks-form-item {
      padding-right: 24px;
    }
    &::-webkit-scrollbar {
      display: none;
    }
    .form-divider-title {
      border-bottom: 1px #eeeeee solid;
      width: 100%;
      margin: 16px 24px;
      padding-bottom: 8px;
      font-size: 14px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333;
      line-height: 20px;
      display: flex;
      align-items: center;
      &:nth-of-type(1) {
        margin-top: 24px;
      }
      i {
        color: var(--theme-color);
        margin-right: 4px;
        margin-bottom: -1px;
        font-size: 16px;
        // color: var(--theme-color);
      }
    }
  }
  &-footer {
    flex-shrink: 0;
    flex-grow: 0;
    display: flex;
    justify-content: space-between;
    padding: 16px 24px;
    margin-top: 16px;
    border-top: 1px #ddd solid;
  }
}

.item-sp-tip {
  font-size: 14px;
  font-family: MicrosoftYaHei;
  color: #cccccc;
  line-height: 19px;
}
</style>